<template>
  <div class="cart-shoppingcart-container">
    <el-container>
      <el-header v-if="!isOrder">
        <el-checkbox v-model="isSelectAll" @change="toggleAll"
          >全选</el-checkbox
        >
        <el-button plain size="small" @click="deleteBatch"
          >删除 <i class="el-icon-delete"></i
        ></el-button>
        <el-button plain size="small" @click="deleteAll">清空购物车</el-button>
      </el-header>
      <el-main>
        <div v-if="cartList.length > 0">
          <div v-for="item in cartList" :key="item.cartId" class="cart-item">
            <div class="sellername">
              <el-tag size="mini" type="warning">卖家</el-tag>
              {{ item.sellerName }}
            </div>
            <div class="cart-content">
              <el-checkbox
                @change="(val) => changeSelect(val, item.cartId)"
                v-model="item.selected"
                :label="item.cartId"
              ></el-checkbox>
              <el-image
                style="width: 120px; height: 120px"
                :src="item.productImage"
              />
              <div class="cart-good-name">
                {{ item.productName }}
                <div class="cart-good-description">
                  <el-tag size="mini" type="info"
                    >&nbsp;{{ item.productDescription }}</el-tag
                  >
                </div>
              </div>
              <div class="cart-good-price">
                ￥{{ item.productPrice }}
                <span style="font-size: 12px; color: #ff5000">近期降价</span>
              </div>
              <div class="cart-good-count">
                <el-input-number
                  size="small"
                  v-model="item.quantity"
                  :min="1"
                  @change="(value) => changeCount(value, item.cartId)"
                ></el-input-number>
              </div>
              <div class="action">
                <el-button
                  plain
                  size="medium"
                  @click="likeByOne(item.cartId, item.productId)"
                  ><i class="el-icon-star-off"></i> 移入收藏</el-button
                >
                <el-button plain size="medium" @click="deleteByOne(item.cartId)"
                  ><i class="el-icon-delete"></i> 删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
        <div v-else>
          <el-empty
            v-if="cartList.length === 0"
            description="暂无数据"
          ></el-empty>
        </div>
      </el-main>
    </el-container>
    <div class="checkout" v-if="!isOrder">
      <div class="checkout-left">
        <el-checkbox v-model="isSelectAll" @change="toggleAll"
          >全选</el-checkbox
        >
        <span class="select-num">已选中{{ selectItems.length }}件商品</span>
      </div>
      <div class="checkout-right">
        <span class="checkout-price">
          <span class="sum-text">合计：</span>
          <span class="sum-price">￥{{ totalAmount }}</span>
        </span>
        <el-button type="danger" @click="gotoCheckout"
          >去结算({{ selectItems.length }})</el-button
        >
      </div>
    </div>
    <el-dialog
      :visible="dialogVisibleDelete"
      width="300px"
      @close="dialogVisibleDelete = false"
    >
      <template slot="title">
        <span> <i class="el-icon-warning-outline"></i>&nbsp;提示</span>
      </template>
      <span style="font-size: 14px"> 确定要删除商品吗？ </span>
      <template slot="footer">
        <el-button @click="dialogVisibleDelete = false" size="mini"
          >取消</el-button
        >
        <el-button type="primary" @click="confirmDelete" size="mini"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import CartTable from "./CartTable";
export default {
  name: "ShoppingCart",
  components: {},
  data() {
    return {
      isSelectAll: false,
      totalAmount: 0,
      selectItems: [],
      cartList: [],
      deleteMode: 0, //0 batch, 1 all, 2 byone
      dialogVisibleDelete: false,
      currentGoodname: "",
      currentCartId: "",
    };
  },
  props: {
    isOrder: {
      type: Boolean,
      default: false,
    },
  },
  created() {
    this.load();
  },
  mounted: function () {},
  methods: {
    load() {
      this.$axios
        .get(`/cart/getUserCart/${this.$store.state.user.userId}`)
        .then((res) => {
          if (res.data.success) {
            this.cartList = res.data.data.reverse();
            this.totalAmount = res.data.totalAmount;
            this.selectItems = res.data.data
              .filter((item) => item.selected)
              .map((item) => item.cartId);
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    changeCount(value, cartId) {
      this.$axios
        .post("/cart/update", {
          cartId: cartId,
          quantity: value,
        })
        .then((res) => {
          if (res.data.success) {
            this.load();
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    changeSelect(value, cartId) {
      if (value) {
        this.selectItems.push(cartId);
      } else {
        let index = this.selectItems.indexOf(cartId);
        this.selectItems.splice(index, 1);
      }
      this.$axios
        .post("/cart/update", {
          cartId: cartId,
          selected: value,
        })
        .then((res) => {
          if (res.data.success) {
            this.load();
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    deleteBatch() {
      if (this.selectItems.length === 0) {
        this.$message.error("请至少选择一项商品");
        return;
      }
      this.deleteMode = 0;
      this.dialogVisibleDelete = true;
    },
    deleteAll() {
      if (this.cartList.length === 0) {
        this.$message.error("请至少选择一项商品");
        return;
      }
      this.deleteMode = 1;
      this.dialogVisibleDelete = true;
    },
    deleteByOne(cartId) {
      this.deleteMode = 2;
      this.currentCartId = cartId;
      this.dialogVisibleDelete = true;
    },
    toggleAll() {
      if (this.isSelectAll) {
        let promiseList = [];
        this.cartList.forEach((item) => {
          item.selected = true;
          let promise = this.$axios.post("/cart/update", {
            cartId: item.cartId,
            selected: true,
          });
          promiseList.push(promise);
        });
        Promise.all(promiseList).then((res) => {
          // console.log(res);
          if (res.every((item) => item.data.success)) {
            this.load();
          } else {
            this.$message.error(res.data.message);
          }
        });
      } else {
        this.cartList.forEach((item) => {
          item.selected = false;
          this.$axios
            .post("/cart/update", {
              cartId: item.cartId,
              selected: false,
            })
            .then((res) => {
              if (res.data.success) {
                this.load();
              } else {
                this.$message.error(res.data.message);
              }
            });
        });
      }
    },
    confirmDelete() {
      // batch
      if (this.deleteMode === 0) {
        this.$axios
          .request({
            url: "/cart/deleteAll",
            method: "DELETE",
            data: this.selectItems, // 传入 cartId 数组
          })
          .then((res) => {
            if (res.data.success) {
              this.$message.success("删除商品成功");
              this.dialogVisibleDelete = false;
              this.load(); // 刷新购物车
            } else {
              this.$message.error(res.data.message);
            }
          });
      } else if (this.deleteMode === 1) {
        //all
        this.$axios
          .request({
            url: "/cart/deleteAll",
            method: "DELETE",
            data: this.cartList.map((item) => item.cartId), // 传入 cartId 数组
          })
          .then((res) => {
            if (res.data.success) {
              this.$message.success("清空购物车成功");
              this.dialogVisibleDelete = false;
              this.load(); // 刷新购物车
            } else {
              this.$message.error(res.data.message);
            }
          });
      } else if (this.deleteMode === 2) {
        //byone
        this.$axios.delete(`/cart/delete/${this.currentCartId}`).then((res) => {
          if (res.data.success) {
            this.$message.success("删除商品成功");
            this.dialogVisibleDelete = false;
            this.load();
          } else {
            this.$message.error(res.data.message);
          }
        });
      }
    },
    likeByOne(cartId, goodsId) {
      console.log(this.$store.state.user.userId);
      this.$axios
        .post("/favorite/add", null, {
          params: {
            userId: this.$store.state.user.userId,
            goodsId: goodsId,
          },
        })
        .then((res) => {
          if (res.data.success) {
            this.$axios.delete(`/cart/delete/${cartId}`).then((res) => {
              if (res.data.success) {
                this.load();
              }
            });
            this.$message.success(res.data.message);
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    gotoCheckout() {
      if (this.selectItems.length === 0) {
        this.$message.error("请至少选择一项商品");
        return;
      }
      this.$router.push("/placeOrders");
    },
  },
  watch: {
    selectItems(newval) {
      if (newval.length === this.cartList.length) {
        this.isSelectAll = true;
      } else {
        this.isSelectAll = false;
      }
    },
  },
};
</script>

<style lang="scss">
.cart-shoppingcart-container {
  background-color: #f7f7f7;
  min-width: 1200px;
  min-height: 800px;
  .el-button {
    border-radius: 10px;
  }
  .el-dialog {
    border-radius: 10px;
  }
  .el-container {
    width: 1000px;
    margin: 0 auto;
    // background-color: #fff;
    .el-header {
      display: flex;
      align-items: center;
      height: 40px !important;
      margin-top: 20px;
      .el-checkbox {
        margin-right: 20px;
      }
    }
    .el-main {
      padding-top: 0;
      padding-bottom: 80px;
      min-height: 800px;
      .el-checkbox__label {
        display: none;
      }
    }
    .cart-item {
      background-color: #fff;
      margin: 20px 0;
      padding: 20px;
      border-radius: 20px;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      text-align: left;
      .sellername {
        margin-left: 30px;
        margin-bottom: 10px;
        font-size: 16px;
        font-weight: 600;
      }
      .cart-content {
        display: flex;
        position: relative;
        .el-image {
          border-radius: 10px;
          padding: 0 10px;
          padding-left: 30px;
          img {
            border-radius: 10px;
          }
        }
        .el-checkbox {
          position: absolute;
          top: 50%;
        }
        .cart-good-name {
          width: 250px;
          font-weight: 600;
          padding: 0 10px;
          color: #3d4040;
          .cart-good-description {
            margin-top: 10px;
            font-size: 12px;
            color: #3e3e3e;
            font-weight: 400;
          }
        }
        .cart-good-count {
          width: 200px;
        }
        .cart-good-price {
          width: 200px;
          font-size: 20px;
          padding: 0 10px;
          font-weight: 600;
          color: #f56c6c;
        }
        .el-button {
          height: 20px;
          border: none;
        }
      }
    }
  }
  .checkout {
    width: 100%;
    min-width: 1000px;
    box-sizing: border-box;
    padding: 0 30px;
    background-color: #fff;
    height: 80px;
    position: fixed;
    bottom: 0;
    border-radius: 10px;
    box-shadow: 0px 2px 10px 1px #0000002a;
    display: flex;
    justify-content: space-between;
    align-items: center;
    z-index: 10;
    overflow: auto;
  }
  .checkout-left {
    .select-num {
      font-size: 14px;
      margin-left: 20px;
      color: #3d3e3e;
      letter-spacing: 1px;
    }
  }
  .sum-text {
    font-size: 14px;
  }
  .checkout-right {
    display: flex;
    .checkout-price {
      display: flex;
      align-items: center;
      margin-right: 30px;
      .sum-price {
        font-size: 24px;
        color: #f56c6c;
        font-weight: 800;
      }
    }
  }
}
</style>